package com.apps.ubc.cc.ajax;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringEscapeUtils;

import com.apps.datastore.dao.BookInformation;
import com.apps.services.UBCSectionDetailService;
import com.apps.services.factory.UBCSectionDetailServiceFactory;

public class BookController extends HttpServlet {

	UBCSectionDetailService w;

	public void doGet(HttpServletRequest req, HttpServletResponse resp) {
		w = UBCSectionDetailServiceFactory.getUBCSectionDetailService();
		StringBuilder builder = new StringBuilder();
		String dept = req.getParameter("dept");
		String course = req.getParameter("course");
		String section = req.getParameter("section");
		builder.append("<booklist>\n");
		// String out = "<booklist>\n";
		if (dept != null && course != null && section != null) {
			w.init(dept, course, section);
			List<BookInformation> biol = new ArrayList<BookInformation>();
			biol.addAll(w.getBookList());
			builder.append("\t<error>none</error>\n");
			// out += "\t<error>none</error>\n";
			for (Iterator<BookInformation> i = biol.iterator(); i.hasNext();) {
				BookInformation bi = i.next();
				builder.append("\t<book>\n");
				builder.append("\t\t<title>"
						+ StringEscapeUtils.escapeXml(bi.getTitle())
						+ "</title>\n");
				builder.append("\t\t<required>"
						+ StringEscapeUtils.escapeXml(bi.getRequired())
						+ "</required>\n");
				builder.append("\t\t<author>"
						+ StringEscapeUtils.escapeXml(bi.getAuthor())
						+ "</author>\n");
				builder.append("\t\t<isbn>" + bi.getISBN() + "</isbn>\n");
				builder.append("\t</book>\n");

				// out += "\t<book>\n";
				// out += "\t\t<title>" +
				// StringEscapeUtils.escapeXml(bi.getTitle()) + "</title>\n";
				// out += "\t\t<required>" +
				// StringEscapeUtils.escapeXml(bi.getRequired()) +
				// "</required>\n";
				// out += "\t\t<author>" +
				// StringEscapeUtils.escapeXml(bi.getAuthor()) + "</author>\n";
				// out += "\t\t<isbn>" + bi.getISBN() + "</isbn>\n";
				// out += "\t</book>\n";
			}
		} else
			builder.append("\t<error>not found</error>\n");
			builder.append("</booklist>");
			
		try {
			String out = builder.toString();
			resp.setContentType("text/xml");
			resp.getWriter().write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
